<?php
namespace Home\Controller;
use Think\Controller;
class WxmpayController extends CommonController {
	
	public function _initialize() {
		parent::_initialize();
		Vendor('Wxmpay.Pubhelper');
		Vendor('Wxmpay.Rexception');
	} 
	
    public function index(){
		
		if ($this->checkLogin() == false) {
			echo '尚未登陆';
			exit;
		}
		$flow_id = I('flow_id','');
		
		//使用jsapi接口
		$jsApi = new \JsApi_pub();

		//=========步骤1：网页授权获取用户openid============
		if (!isset($_GET['code'])){
			$url = $jsApi->createOauthUrlForCode(urlencode(C('WXMPAY_CONFIG.JS_API_CALL_URL')."?showwxpaytitle=1&flow_id=".$flow_id));
			Header("Location: $url"); 
		}else{
			$code = $_GET['code'];
			$jsApi->setCode($code);
			$openid = $jsApi->getOpenId();
		}
		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new \UnifiedOrder_pub();
		$unifiedOrder->setParameter("openid",$openid);//用户标识
		$unifiedOrder->setParameter("body","食市移动支付");//商品描述

		$onlinePayFlowSrv = D('PaymentOnlineFlow');
		$flowInfo = $onlinePayFlowSrv->where("flow_id = '".$flow_id."'")->find();
		if(empty($flowInfo) || $flowInfo['status']!=0){//回订单中心
			redirect('/#/ordercenter', 0, '');
		}
		$total_fee = num_f($flowInfo['should_pay']);
		$out_trade_no = $flow_id;
		
		$unifiedOrder->setParameter("out_trade_no",$out_trade_no);//商户订单号 
		$unifiedOrder->setParameter("total_fee",num_f($total_fee*100));//总金额 单位分
		$unifiedOrder->setParameter("notify_url",C('WXMPAY_CONFIG.NOTIFY_URL'));//通知地址 
		$unifiedOrder->setParameter("trade_type","JSAPI");//交易类型


		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);

		$jsApiParameters = $jsApi->getParameters();
		
		$html_all = '<html>
		<head>
			<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
			<head>
			<style>
			.pay{
				font-size: 2.25rem;
				color: #fff;
				background-color: #ee6156;
				border-color: #ec4b3f;
				padding: 6px 12px;
				border-radius: 4px;
			}
			.done{
				font-size: 2.25rem;
				color: #fff;
				background-color: #43CD80;
				border-color: #43CD80;
				padding: 6px 12px;
				border-radius: 4px;
			}
			</style>
			</head>
			<title>食市移动支付</title>
			<script type="text/javascript">
				function jsApiCall(){
					WeixinJSBridge.invoke(
						"getBrandWCPayRequest",
						'.$jsApiParameters.',
						function(res){
							WeixinJSBridge.log(res.err_msg);
						}
					);
				}

				function callpay(){
					if (typeof WeixinJSBridge == "undefined"){
						if( document.addEventListener ){
							document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
						}else if (document.attachEvent){
							document.attachEvent("WeixinJSBridgeReady", jsApiCall); 
							document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
						}
					}else{
						jsApiCall();
					}
				}
				callpay();
			</script>
		</head>
		<body>
			</br></br></br></br>
			<div class="row">
				<div style="text-align:center; width:100%">
					<a href="#" onclick="callpay()"><button type="button" class="pay">重新支付</button></a>
					</br></br></br></br>
					<a href="/#/ordercenter"><button type="button" class="done" >支付完成</button></a>
				</div>
			</div>
		</body>
		</html>';
		$this->show($html_all);
    }
	
	
	public function notifyUrl(){
		sys_pay_log("************************wxmpay_notify start*****************************");
		sys_pay_log(yzg_json_encode($_REQUEST));
		
		
		//使用通用通知接口
		$notify = new \Notify_pub();

		//存储微信的回调
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];	
		$notify->saveData($xml);
		
		//验证签名，并回应微信。
		//对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
		//微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
		//尽可能提高通知的成功率，但微信不保证通知最终能成功。
		if($notify->checkSign() == FALSE){
			$notify->setReturnParameter("return_code","FAIL");//返回状态码
			$notify->setReturnParameter("return_msg","签名失败");//返回信息
		}else{
			$notify->setReturnParameter("return_code","SUCCESS");//设置返回码
		}
		$returnXml = $notify->returnXml();
		echo $returnXml;
		
		//==商户根据实际情况设置相应的处理流程，此处仅作举例=======
		
		//以log文件形式记录回调信息
		sys_pay_log("returnXml : ".$returnXml);
		sys_pay_log("【接收到的notify通知】:\n".$xml."\n");

		if($notify->checkSign() == TRUE){
			if ($notify->data["return_code"] == "FAIL") {
				//此处应该更新一下订单状态，商户自行增删操作
				sys_pay_log("【通信出错】:\n".$xml."\n");
			}elseif($notify->data["result_code"] == "FAIL"){
				//此处应该更新一下订单状态，商户自行增删操作
				sys_pay_log("【业务出错】:\n".$xml."\n");
			}else{
				//此处应该更新一下订单状态，商户自行增删操作
				// sys_pay_log("************************log start*****************************");
				// sys_pay_log("notify->data:");
				// sys_pay_log(yzg_json_encode($notify->data));
				// sys_pay_log("************************log end*****************************");
				
				$paySrv = D('PaymentInfo');
				$paySrv->completeOnlinePayFlow($notify->data['out_trade_no'],C('WXMPAY_PREFIX') .$notify->data['transaction_id'],C('PAYMENT_TYPE.WXMPAY'));
				
				sys_pay_log("【支付成功】:\n".$xml."\n");
			}
		}
		sys_pay_log("************************wxmpay_notify end*****************************");
	}
	
	public function alarmnotify(){
		
	}
	
}